package org.lex.keytool.ui;

import java.awt.Window;
import java.io.IOException;
import java.io.Writer;
import java.util.concurrent.ExecutionException;

import javax.swing.JDialog;
import javax.swing.SwingWorker;

import org.lex.keytool.KeyTool;
import org.lex.keytool.core.runner.ForkTaskRunner;
import org.lex.keytool.core.task.Task;

public class ProgressOutputDialog extends JDialog {
	public static void runTask(Task task) {
		new ProgressOutputDialog(KeyTool.getInstance().getMainFrame()).run(task);
	}

	private ProcessOutputPane contentPane = null;

	public ProgressOutputDialog(Window parent) {
		super(parent);
		this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
		this.setModal(true);
		this.setSize(300, 300);
		this.setTitle("Running...");
		this.setLocationRelativeTo(parent);

		this.initComponents();
	}

	public void run(final Task task) {
		new SwingWorker<Integer, Void>() {
			Writer out = contentPane.getStdoutWriter();
			Writer err = contentPane.getStderrWriter();

			@Override
			protected Integer doInBackground() {
				ForkTaskRunner runner = new ForkTaskRunner(out, err);
				try {
					return runner.run(task).get();
				} catch (InterruptedException e) {
					e.printStackTrace();
				} catch (ExecutionException e) {
					e.printStackTrace();
				} catch (Exception e) {
					e.printStackTrace();
				}
				return 1;
			}

			@Override
			protected void done() {
				try {
					int ret = this.get();
					System.out.println("Task finished with returnValue=" + ret);
					contentPane.setProcessFinished(true);
					setTitle("Task Finished");
					out.write("\nTask finished with return value=" + ret);
				} catch (InterruptedException e) {
					e.printStackTrace();
				} catch (ExecutionException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}.execute();
		this.setVisible(true);
	}

	private void initComponents() {
		this.contentPane = new ProcessOutputPane();
		this.setContentPane(contentPane);
	}
}
